package com.xmy.cultivate.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.xmy.cultivate.entity.*;
import com.xmy.cultivate.exception.CommonException;
import com.xmy.cultivate.mapper.*;
import com.xmy.cultivate.service.ICourseService;
import com.xmy.cultivate.service.IOrderDetailService;
import com.xmy.cultivate.service.IQuarterService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmy.cultivate.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 每年季度 服务实现类
 * </p>
 *
 * @author min
 * @since 2022-08-22
 */
@Service
public class QuarterServiceImpl extends ServiceImpl<QuarterMapper, Quarter> implements IQuarterService {

    @Autowired
    @Lazy
    QuarterMapper quarterMapper;

    @Autowired
    @Lazy
    OrderDetailMapper orderDetailMapper;

    @Autowired
    @Lazy
    IOrderDetailService iOrderDetailService;

    @Autowired
    @Lazy
    ICourseService iCourseService;

    @Autowired
    @Lazy
    IdWorker idWorker;

    @Autowired
    @Lazy
    StudentGradeMapper studentGradeMapper;

    @Autowired
    @Lazy
    GradeMapper gradeMapper;

    @Autowired
    @Lazy
    CompanyMapper companyMapper;

    @Autowired
    @Lazy
    IQuarterService iQuarterService;

    @Autowired
    @Lazy
    RenewDataMapper renewDataMapper;


    public List<Map<String,Object>> getYearPartList(){
        return quarterMapper.getYearPartList();
    }

    public IPage<Map<String,Object>> findAll(IPage<?> page, Wrapper wrapper){
        return quarterMapper.findAll(page,wrapper);
    }

    public boolean saveTo(Quarter quarter){

        List<Quarter> quarterList = new ArrayList<>();
        List<Quarter> upQuarterList = new ArrayList<>();

        Iterator<Quarter> quarterIterator = quarter.getQuarterList().iterator();
        while (quarterIterator.hasNext()){
            Quarter quarter1 = quarterIterator.next();
            if(quarter1.getId()!=null && quarter1.getId() !=0){
                //添加
                quarterList.add(quarter1);
            }else {
                upQuarterList.add(quarter1);
            }
        }
        if(quarterList.size()>0){
            this.saveBatch(quarterList);
        }

        if(upQuarterList.size()>0){
            this.updateBatchById(upQuarterList,upQuarterList.size());
        }

        return true;
    }



    /**
     * 根据季度获取年份
     * @param newNum
     * @return
     */
    public Integer getQuarterYearPartForNum(Integer newNum){
        LocalDate nowDate = DateUtil.getNowDate();
        //指定日期
        Company company = companyMapper.selectById(1L);
        if(company.getIsUseEnrollYear() == 1){
            nowDate = company.getEnrollYear();
        }


        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("start_date",nowDate).ge("end_date",nowDate);

        //获取当前时间所属的季度
        Quarter quarterNow = quarterMapper.selectOne(queryWrapper);
        if(quarterNow == null){
            //季度不存在，请先添加季度
            throw new CommonException(ResultCode.quarterNo);
        }
        Integer nowQuarterNum = quarterNow.getNum();

        //通过当前的季度，获取报读的年份
        //获取当前报读的年份
        Integer nowYeartPart = quarterNow.getYearPart();
        Integer newYeartPart = nowYeartPart;

        //nowQuarterNum:当前时间所属的季度，newNum：报读的季度
        if(nowQuarterNum > newNum){
            //属于下一年的季度
            newYeartPart = nowYeartPart + 1;
        }
        return newYeartPart;
    }


    /**
     * Long schoolId,Long studentId,Long subjectId,Integer quarterNum
     * @param schoolId
     * @param studentId
     * @param subjectId
     * @param quarterNum
     * @return
     * @throws ParseException
     */
    public RenewClass getRenewForPay(Long schoolId,Long studentId,Long subjectId,Integer quarterNum) throws ParseException {

        RenewClass renewClass = new RenewClass();

        Integer year_part = iQuarterService.getQuarterYearPartForNum(quarterNum);//获取报读的年份
        //System.out.print("year_part:"+year_part);


        QueryWrapper<RenewData> renewDataQueryWrapper = new QueryWrapper<>();
        renewDataQueryWrapper.eq("school_id",schoolId);
        renewDataQueryWrapper.eq("subjects_id",subjectId);
        renewDataQueryWrapper.eq("student_id",studentId);
        renewDataQueryWrapper.eq("year_part_renew",year_part);
        renewDataQueryWrapper.eq("quarter_num_renew",quarterNum);
        renewDataQueryWrapper.eq("type",1);
        RenewData renewData = renewDataMapper.selectOne(renewDataQueryWrapper);

        String rsStr = "";

        //为空表示没有需要续班的信息
        if(renewData != null){
            //还没有续班成功
            if(renewData.getIsRenew()!=1){
                String quarterName = ConfigData.getQuarterForNum(renewData.getQuarterNum());
                String quarterNameRenew = ConfigData.getQuarterForNum(renewData.getQuarterNumRenew());
                rsStr = quarterName+"续"+quarterNameRenew;
            }
            renewClass.setYearPart(year_part);
            renewClass.setRenewType(1);
            renewClass.setTypeName(rsStr);
        }else{
            QueryWrapper<RenewData> renewDataQueryWrapperNext = new QueryWrapper<>();
            renewDataQueryWrapperNext.eq("school_id",schoolId);
            renewDataQueryWrapperNext.eq("subjects_id",subjectId);
            renewDataQueryWrapperNext.eq("student_id",studentId);
            renewDataQueryWrapperNext.eq("year_part_renew",year_part);
            renewDataQueryWrapperNext.eq("quarter_num_renew",quarterNum);
            renewDataQueryWrapperNext.eq("type",2);
            RenewData renewDataNext = renewDataMapper.selectOne(renewDataQueryWrapperNext);

            if(renewDataNext!=null){
                if(renewDataNext.getIsRenew() != 1){
                    String quarterName = ConfigData.getQuarterForNum(renewDataNext.getQuarterNum());
                    String quarterNameRenew = ConfigData.getQuarterForNum(renewDataNext.getQuarterNum());
                    rsStr = quarterName+"续"+quarterNameRenew;
                }
                renewClass.setRenewType(1);
                renewClass.setTypeName(rsStr);
            }else{
                String quarterName = ConfigData.getQuarterForNum(quarterNum);
                renewClass.setYearPart(year_part);
                renewClass.setRenewType(0);
                renewClass.setTypeName(quarterName);
                renewClass.setQuarterName(quarterName);
            }
        }

        return renewClass;
    }



    public Quarter getNowQuarter(){
        LocalDate nowDate = LocalDate.now();
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.le("start_date",nowDate);
        queryWrapper.ge("end_date",nowDate);
        queryWrapper.last("limit 1");
        Quarter quarter = iQuarterService.getOne(queryWrapper);
        return quarter;
    }

    /**
     * 根据年份与学期获取一条数据
     * @param yearPart
     * @param quarterNum
     * @return
     */
    @Override
    public Quarter getOneForYearAndNum(Integer yearPart,Integer quarterNum){
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year_part",yearPart);
        queryWrapper.eq("num",quarterNum);
        queryWrapper.last("limit 1");
        Quarter quarter = this.getOne(queryWrapper);
        return quarter;
    }


    /**
     * 获取结束id最大的一条数据
     * @param endId
     * @return
     */
    @Override
    public Quarter getQuarterMaxForId(Integer endId){
        return quarterMapper.getQuarterMaxForId(endId);
    }

    @Override
    public Integer getIdForYearPartAndNum(Integer yearPart,Integer quarterNum){
        return quarterMapper.getIdForYearPartAndNum(yearPart,quarterNum);
    }

    @Override
    public Quarter getQuarterForYearAndNum(Integer yearPart, Integer num) {
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("year_part",yearPart);
        queryWrapper.eq("num",num);
        queryWrapper.last("limit 1");
        Quarter quarter = quarterMapper.selectOne(queryWrapper);
        return quarter;
    }

    /**
     * 获取前面第几个学期
     * @param yearPart
     * @param quarterNum
     * @param upNum
     * @return
     */
    @Override
    public Quarter getUpQuarter(Integer yearPart, Integer quarterNum, Integer upNum){
        Quarter quarter = this.getOneForYearAndNum(yearPart,quarterNum);
        QueryWrapper<Quarter> queryWrapper = new QueryWrapper<>();
        Integer upNumId = Integer.parseInt(quarter.getId().toString()) - upNum;
        if (upNumId<1){
            upNumId = 1;
        }
        queryWrapper.eq("id",upNumId);
        Quarter upQuarter = this.getOne(queryWrapper);
        return upQuarter;
    }

}
